from ezp_util import *
import os
import pdb
import string

from ConfigParser import SafeConfigParser

# ---------------------------------------------------------------------------
def get_value_list(item_name, section, cfg, index=0):
    """
    Get a list of values for item_name from section of cfg.
    """
    try:
        cval = cfg.get(section, item_name + '_options')
    except ESGPublishError:
        return []

    vlist = []
    if type(cval) == str:
        if '|' in cval:
            q = splitRecord(cval)
            vlist = [x[index] for x in q]
        elif ',' in cval:
            vlist = [v.strip() for v in cval.split(',')]
    elif type(cval) == list:
        if type(cval[0]) == list:
            vlist = [x[index] for x in cval]
        else:
            vlist = cval
    return vlist

#---------------------------------------------------------------------------
def loadConfig(filename=None):
    """
    The esgcet version of this routine searches all over the place for
    esg.ini. We just want the one that's bundled with ezpub, so we
    just look in the ezpub directory.
    """
    cfg = SafeConfigParser()
    # cfg.set('initialize', 'home', os.getcwd())
    if filename == None:
        filename = "%s/ezpub/esg.ini" % scigest_home()
    cfg.read(filename)
    return cfg

# ---------------------------------------------------------------------------
def loadModels(cfg):
    """
    Load the information in the models table file.
    """
    filename = cfg.get('initialize', 'initial_models_table')

    path = "%s/ezpub/esgcet_models_table.txt" % scigest_home()
    M = textTableIter(path)
    
    mtable = {}
    for z, minfo in M:
        try:
            mtable[minfo[0]].append(minfo[1])
        except:
            mtable[minfo[0]] = []
            mtable[minfo[0]].append(minfo[1])
    return mtable

# ---------------------------------------------------------------------------
def project_list():
    cfg = loadConfig("./esg.ini")
    rval = get_value_list('project', 'DEFAULT', cfg)
    return rval

# ---------------------------------------------------------------------------
def read_app_props(propname):
    plist = contents("%s/.scigest/application.properties" % user_home(), False)
    for line in plist:
        if "=" in line:
            (prop, val) = line.split("=")
            if prop.strip() == propname:
                return val.strip()

# ---------------------------------------------------------------------------
def splitLine(line, sep='|'):
    """Split a line into fields.
    
    Returns a list of string fields.

    line
       String line to split.

    sep
       Separator character.
    """
    fields = map(string.strip, line.split(sep))
    return fields

# ---------------------------------------------------------------------------
def splitRecord(option, sep='|'):
    """
    Split a multi-line record in a .ini file.
 
    Returns a list of the form [[field, field, ...], [field, field, ...]]

    option
      String option in the .ini file.

    sep
      Separator character.

    For example, if the init file option is::

        creator_options =
          Contact_1 | foo | http://bar
          Contact_2 | boz@bat.net |
 
    then the code::

        lines = config.get(section, 'creator_options')
        result = splitRecord(lines)

    returns::

        [['Contact_1', 'foo', 'http://bar'], ['Contact_2', 'boz@bat.net', '']]

    """
    result = []
    for record in option.split('\n'):
        if record=='':
            continue
        fields = map(string.strip, record.split(sep))
        result.append(fields)

    return result
                                            
# ---------------------------------------------------------------------------
def textTableIter(path, sep='|', splitter=splitLine):
    """
    Iterator that returns a list of options corresponding to one record.
    """
    f = open(path)
    line = f.readline()
    lineno = 0
    while line:
        lineno += 1
        line = line.strip()
        if len(line)>0 and line[0]!='#':
            yield lineno, splitter(line)
        line = f.readline()
    return
                                                                
